<!doctype html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">

<head>
    <!-- 原始地址：//webapi.amap.com/ui/1.0/ui/misc/PathSimplifier/examples/simple-demo.html -->
    <!--<base href="https://webapi.amap.com/ui/1.0/ui/misc/PathSimplifier/examples/" />-->
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width, shrink-to-fit=no">
    <title>火车线路图</title>

    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <style>
        html,
        body,
        #mapContainer {
            width: 100%;
            height: 600px;
            #margin: 10px;
        }
    </style>

</head>

<body>

<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
    <a class="navbar-brand" href="#">火车线路图</a>
</nav>

<div class="container-fluid mt-2">
    <div class="row">
        <div class="col-sm-12">

            <div class="form-inline">
                <label>请输入车次:</label>
                <input type="text" class="form-control ml-2" placeholder="请输入车次" id="code" autocomplete="off">
                <button type="submit" class="btn btn-primary ml-2" onclick="search()">查询</button>
                <button type="submit" class="btn btn-danger ml-2" onclick="location.reload()">刷新</button>
                <label class="ml-5" id="trainNumberMsg"></label>
            </div>

        </div>

    </div>

    <div class="row mt-2">
        <div class="col-sm-12" >
            <div id="mapContainer"></div>
        </div>
    </div>

</div>


<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.bootcss.com/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.bootcss.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<script type="text/javascript" th:src="@{${amapWebApi}}"></script>

<!-- UI组件库 1.0 -->
<script src="https://webapi.amap.com/ui/1.0/main.js?v=1.0.11"></script>
<script type="text/javascript">

    function search(){
        //alert($("#code").val());
        var code = $("#code").val();
        if(code == null || code == ""){
            alert("请输入车次");
            return false;
        }


        $.get("/train/timetable/" + code, function(data){
            if(data.code == 200){
                var result = data.data;
                if(result != null && result.trainTimetableList != null){
                    $("#trainNumberMsg").html(result.code + " " +  result.fromStation + '（' + result.trainTimetableList[0].startTime + '）' + " -> " + result.toStation + '（' + result.trainTimetableList[result.trainTimetableList.length-1].startTime + '）');
                    var name = result.code + "：" +  result.fromStation + " -> " + result.toStation;
                    var path = [];
                    var stationData = [];
                    for(var i in result.trainTimetableList){
                        var lngLat = [result.trainTimetableList[i].trainStation.lng, result.trainTimetableList[i].trainStation.lat];
                        path.push(lngLat);
                        stationData.push(result.trainTimetableList[i]);
                    }

                    var pathData = [{name: name, path: path, stationData: stationData}];
                    console.log(pathData);
                    pathSimplifierIns.setData(pathData);
                }
            }else{
                alert(data.msg);
            }
        })

    }

    //创建地图
    var map = new AMap.Map('mapContainer', {
        zoom: 4
    });

    map.plugin('AMap.Geolocation', function() {
        var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            timeout: 10000,
            // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
            buttonOffset: new AMap.Pixel(10, 20),
            //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            zoomToAccuracy: true,
            //  定位按钮的排放位置,  RB表示右下
            buttonPosition: 'RB'
        })

        map.addControl(geolocation);

        geolocation.getCurrentPosition()
        AMap.event.addListener(geolocation, 'complete', onComplete)
        AMap.event.addListener(geolocation, 'error', onError)

        function onComplete (data) {
            // data是具体的定位信息
            console.log("===dw===");
            console.log(data);
        }

        function onError (data) {
            // 定位出错
        }
    })

    AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], function(PathSimplifier, $) {

        if (!PathSimplifier.supportCanvas) {
            alert('当前环境不支持 Canvas！');
            return;
        }

        var pathSimplifierIns = new PathSimplifier({
            zIndex: 100,
            //autoSetFitView:false,
            map: map, //所属的地图实例

            getPath: function(pathData, pathIndex) {

                return pathData.path;
            },
            getHoverTitle: function(pathData, pathIndex, pointIndex) {

                if (pointIndex >= 0) {
                    //point
                    var trainTimetable = pathData.stationData[pointIndex];
                    var timetableMsg = trainTimetable.arriveTimeFlag==0?'当日':'次日';
                    if(pointIndex == 0){//始发
                        timetableMsg += trainTimetable.startTime + '始发';
                    }else if(pointIndex == pathData.path.length-1){//终点
                        timetableMsg += trainTimetable.arriveTime + '到达终点';
                    }else{
                        timetableMsg += trainTimetable.arriveTime + '到达，'+ trainTimetable.startTime + '发车';
                    }
                    return trainTimetable.trainStation.name + ' (' + trainTimetable.trainStation.province + trainTimetable.trainStation.city + ')' + '<br/>' +  timetableMsg;
                }

                return pathData.name + '，共有' + pathData.path.length + '站';
            },
            renderOptions: {

                renderAllPointsIfNumberBelow: 100 //绘制路线节点，如不需要可设置为-1
            }
        });

        window.pathSimplifierIns = pathSimplifierIns;

        //设置数据
        /*        pathSimplifierIns.setData([{
                    name: '路线0',
                    path: [
                        [116.405289, 39.904987],
                        [113.964458, 40.54664],
                        [111.47836, 41.135964],
                        [108.949297, 41.670904],
                        [106.380111, 42.149509],
                        [103.774185, 42.56996],
                        [101.135432, 42.930601],
                        [98.46826, 43.229964],
                        [95.777529, 43.466798],
                        [93.068486, 43.64009],
                        [90.34669, 43.749086],
                        [87.61792, 43.793308]
                    ]
                }]);*/

        //对第一条线路（即索引 0）创建一个巡航器
        /*  var navg1 = pathSimplifierIns.createPathNavigator(0, {
              loop: true, //循环播放
              speed: 1000000 //巡航速度，单位千米/小时
          });*/

        //navg1.start();

        // navg1.moveToPoint(2, 0.5);

    });



    var geocoder;
    function geoCode(address) {
        if(!geocoder){

            map.plugin('AMap.Geocoder', function() {
                geocoder = new AMap.Geocoder({
                    city: "全国", //城市设为北京，默认：“全国”
                });
            })

        }

        geocoder.getLocation(address, function(status, result) {
            console.log(result);
            if (status === 'complete'&&result.geocodes.length) {
                var lnglat = result.geocodes[0].location;
                console.log(lnglat.lng); //经度
                console.log(lnglat.lat); //维度
            }else{
                console.log('根据地址查询位置失败');
            }
        });
    }

    //geoCode('集宁南站');

</script>
</body>

</html>